<template>
  <transition name="el-zoom-in-center">
    <div class="jsbos-preview-main">
      <div class="jsbos-common-page-header">
        <el-page-header
          @back="goBack"
          :content="!dataForm.id ? '新建' : '编辑'"
        />
        <div class="options">
          <el-button type="primary" @click="dataFormSubmit()"> 保 存</el-button>
          <el-button @click="goBack"> 取 消</el-button>
        </div>
      </div>
      <el-row
        :gutter="15"
        class="main"
        :style="{ margin: '0 auto', width: '100%' }"
      >
        <el-form
          ref="elForm"
          :model="dataForm"
          :rules="rules"
          size="small"
          label-width="100px"
          label-position="right"
        >
          <template v-if="!loading">
            <el-col :xs="24" :md="24" :lg="12" :xl="12">
              <el-form-item label="名称" prop="fullName">
                <el-input
                  v-model="dataForm.fullName"
                  placeholder="请输入"
                  clearable
                  :style="{ width: '100%' }"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24" :lg="12" :xl="12">
              <el-form-item label="编码" prop="enCode">
                <el-input
                  v-model="dataForm.enCode"
                  placeholder="请输入"
                  clearable
                  :style="{ width: '100%' }"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24" :lg="12" :xl="12">
              <el-form-item label="业务系统" prop="taskCode">
                <el-select
                  v-model="dataForm.taskCode"
                  placeholder="请选择"
                  clearable
                  :style="{ width: '100%' }"
                >
                  <el-option
                    v-for="(item, index) in taskCodeOptions"
                    :key="index"
                    :label="item.fullName"
                    :value="item.enCode"
                    :disabled="item.disabled"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24" :lg="12" :xl="12">
              <el-form-item label="模板类型" prop="templateType">
                <el-select
                  disabled
                  v-model="dataForm.templateType"
                  placeholder="请选择"
                  clearable
                  :style="{ width: '100%' }"
                >
                  <el-option
                    v-for="(item, index) in templateTypeOptions"
                    :key="index"
                    :label="item.fullName"
                    :value="item.id"
                    :disabled="item.disabled"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24" :lg="12" :xl="12">
              <el-form-item label="消息场景" prop="messageSource">
                <McBusinessDialog
                  v-model="dataForm.messageSource"
                  :title="dataForm.messageSourceName"
                  @change="onMessageSourceChange"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24" :lg="12" :xl="12">
              <el-form-item label="排序码" prop="sortCode">
                <el-input-number
                  v-model="dataForm.sortCode"
                  placeholder="数字文本"
                  :step="1"
                  controls-position="right"
                  :style="{ width: '100%' }"
                >
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24" :lg="12" :xl="12">
              <el-form-item label="状态" prop="enabledMark">
                <el-switch
                  v-model="dataForm.enabledMark"
                  :active-value="1"
                  :inactive-value="0"
                >
                </el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="说明" prop="description">
                <el-input
                  v-model="dataForm.description"
                  placeholder="请输入"
                  :style="{ width: '100%' }"
                  true
                  type="textarea"
                  :autosize="{ minRows: 2, maxRows: 4 }"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label-width="0">
                <div class="jsbos-common-title">
                  <h2></h2>
                </div>
                <el-table :data="dataForm.sendTemplateList" :key="itemKey">
                  <el-table-column
                    type="index"
                    width="50"
                    label="序号"
                    :align="'center'"
                  />
                  <el-table-column prop="messageTypeName" label="消息渠道">
                  </el-table-column>
                  <el-table-column prop="templateEnCode" label="模板编码">
                  </el-table-column>
                  <el-table-column prop="templateName" label="模板名称">
                  </el-table-column>
                  <el-table-column prop="accountEnCode" label="应用编码">
                  </el-table-column>
                  <el-table-column prop="accountName" label="应用名称">
                  </el-table-column>
                  <el-table-column prop="enabledMark" label="状态">
                    <template slot-scope="scope">
                      <el-switch
                        v-model="scope.row.enabledMark"
                        :active-value="1"
                        :inactive-value="0"
                      >
                      </el-switch>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="100">
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        type="text"
                        @click="addOrUpdateTemplate(scope.row, scope.$index)"
                        >编辑
                      </el-button>
                      <el-button
                        size="mini"
                        type="text"
                        class="jsbos-table-delBtn"
                        @click="delSendTemplateList(scope.$index)"
                        >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
                <div class="table-actions" @click="addOrUpdateTemplate()">
                  <el-button type="text" icon="el-icon-plus">添加</el-button>
                </div>
              </el-form-item>
            </el-col>
          </template>
        </el-form>
      </el-row>
      <FormTemplate
        v-if="templateVisible"
        ref="FormTemplateRef"
        :messageSource="dataForm.messageSource"
        @changeTemplateList="changeTemplateList"
      ></FormTemplate>
    </div>
  </transition>
</template>
<script>
import { getInfo, Update, Create } from "@/views/message/api/mcMsgSend";
import McBusinessDialog from "@/views/message/mcBusiness/mcBusinessDialog.vue";
import FormTemplate from "./FormTemplate";
export default {
  components: { McBusinessDialog, FormTemplate },
  props: [],
  data() {
    return {
      visible: false,
      loading: false,
      templateVisible: false,
      dataForm: {
        fullName: "",
        enCode: "",
        taskCode: "",
        templateType: "",
        messageSource: "",
        messageSourceName: "",
        sortCode: 0,
        enabledMark: 1,
        description: "",
        sendTemplateList: [],
      },
      rules: {
        fullName: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
        ],
        enCode: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
        ],
        messageSource: [
          {
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],
      },
      templateTypeOptions: [
        { fullName: "自定义模板", id: "0" },
        { fullName: "系统模板", id: "1" },
      ],
      taskCodeOptions: [],
      taskCodeProps: {
        label: "fullName",
        value: "enCode",
      },
      // 在tableData赋值的地方，顺便随机设置下key，页面就会刷新了
      itemKey: Math.random(),
    };
  },
  computed: {},
  watch: {},
  created() {
    this.getTaskCodeOptions();
  },
  mounted() {},
  methods: {
    getTaskCodeOptions() {
      this.$store
        .dispatch("base/getDictionaryData", {
          encode: "taskCode",
        })
        .then((res) => {
          this.taskCodeOptions = res;
        });
    },
    /**消息场景change事件 */
    onMessageSourceChange(id, item) {
      if (!id) return (this.dataForm.messageSourceName = "");
      this.dataForm.messageSourceName = item.fullName;
      this.dataForm.sendTemplateList = [];
    },
    mcmsgsendtemplateExist() {
      let isOk = true;
      for (let i = 0; i < this.dataForm.sendTemplateList.length; i++) {
        const e = this.dataForm.sendTemplateList[i];
      }
      return isOk;
    },
    goBack() {
      this.$emit("refresh");
    },
    clearData(data) {
      for (let key in data) {
        if (data[key] instanceof Array) {
          data[key] = [];
        } else if (data[key] instanceof Object) {
          this.clearData(data[key]);
        } else {
          data[key] = "";
        }
      }
    },
    init(id) {
      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["elForm"].resetFields();
        if (this.dataForm.id) {
          this.loading = true;
          getInfo(this.dataForm.id).then((res) => {
            this.dataInfo(res.data);
            this.loading = false;
          });
        } else {
          this.clearData(this.dataForm);
          this.dataForm.enabledMark = 1;
          this.dataForm.templateType = "0";
          this.dataForm.sortCode = 0;
        }
      });
      this.$store.commit("generator/UPDATE_RELATION_DATA", {});
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          if (!this.mcmsgsendtemplateExist()) return;

          var _data = this.dataList();
          this.btnLoading = true;
          const formMethod = this.dataForm.id ? Update : Create;
          formMethod(_data)
            .then((res) => {
              this.$message({
                message: res.msg,
                type: "success",
                duration: 1000,
                onClose: () => {
                  this.visible = false;
                  this.btnLoading = false;
                  this.$emit("refresh", true);
                },
              });
            })
            .catch(() => {
              this.btnLoading = false;
            });
        }
      });
    },
    changeTemplateList(data, index) {
      if (!isNaN(index)) {
        let item = this.dataForm.sendTemplateList[index];
        this.dataForm.sendTemplateList[index] = Object.assign({}, item, data);
      } else {
        this.dataForm.sendTemplateList.push(Object.assign({}, data));
      }
      this.itemKey = Math.random();
    },
    addOrUpdateTemplate(data, index) {
      if (this.$isEmpty(this.dataForm.messageSource)) {
        return this.$message.warning("请选择消息场景");
      }

      var _data = data ? JSON.parse(JSON.stringify(data)) : data;
      var _index = index ? parseInt(index) : index;
      this.templateVisible = true;
      this.$nextTick(() => {
        this.$refs.FormTemplateRef.init(_data, _index);
      });
    },
    delSendTemplateList(index) {
      this.dataForm.sendTemplateList.splice(index, 1);
    },
    dataList() {
      var _data = JSON.parse(JSON.stringify(this.dataForm));
      _data.enabledMark = parseInt(_data.enabledMark);
      for (let i = 0; i < _data.sendTemplateList.length; i++) {
        var _list = _data.sendTemplateList[i];
        _list.enabledMark = parseInt(_list.enabledMark);
      }
      return _data;
    },
    dataInfo(dataAll) {
      let _dataAll = dataAll;
      _dataAll.enabledMark = parseInt(_dataAll.enabledMark);
      for (let i = 0; i < _dataAll.sendTemplateList.length; i++) {
        var _list = _dataAll.sendTemplateList[i];
        _list.enabledMark = parseInt(_list.enabledMark);
      }
      this.dataForm = _dataAll;
    },
  },
};
</script>
